package org.gongliang.jsmile.config.oss.cloud;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.gongliang.jsmile.common.enums.KException;
import org.gongliang.jsmile.common.exception.JSmileException;
import org.gongliang.jsmile.config.oss.OSSConfig;
import org.gongliang.jsmile.config.oss.OSSService;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.google.common.collect.Lists;

/**
 * 阿里云oss
 * 
 * @author 亮仔
 *
 */
public class AliyunService extends OSSService {

	private OSS  client;

	public AliyunService() {
		this.config = OSSConfig.me();

		// 初始化
		init();
	}

	private void init() {
		client = new OSSClientBuilder().build(config.getAliyunEndPoint(), config.getAliyunAccessKeyId(),
				config.getAliyunAccessKeySecret());
	}

	@Override
	public String upload(byte[] data, String path) {
		return upload(new ByteArrayInputStream(data), path);
	}

	@Override
	public String upload(InputStream inputStream, String path) {
		try {
			client.putObject(config.getAliyunBucketName(), path, inputStream);
		} catch (Exception e) {
			throw new JSmileException(KException.FILE_UPLOAD_ERROR, e);
		}

		return config.getAliyunDomain() + "/" + path;
	}

	@Override
	public String down(String path, String localPath) {
		OSSObject ossObject = client.getObject(config.getAliyunBucketName(), path);
		try {
			org.apache.commons.io.FileUtils.copyInputStreamToFile(ossObject.getObjectContent(), new File(localPath));
		} catch (IOException e) {
			throw new JSmileException(KException.FILE_DOWN_ERROR, e);
		}
		return null;
	}

	@Override
	public void delete(String path) {
		client.deleteObject(config.getAliyunBucketName(), path);
	}

	@Override
	public List<String> listFiles(String path) {
		List<String> urls = Lists.newArrayList();
		ObjectListing list = client.listObjects(config.getAliyunBucketName(), path);
		List<OSSObjectSummary> sums = list.getObjectSummaries();
		for (OSSObjectSummary s : sums) {
			String picUrl = OSSConfig.me().getAliyunDomain() + "/" + s.getKey();
			urls.add(picUrl);
		}
		return urls;
	}

}
